/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JFrameCliente.java
 *
 * Created on 19/05/2009, 23:38:52
 */
package br.unifor.sd.bolsa.cliente.gui;

import br.unifor.sd.bolsa.interfaces.ClienteBridge;
import br.unifor.sd.bolsa.interfaces.ListListener;
import br.unifor.sd.bolsa.rmi.ClienteImplRMI;
import br.unifor.sd.bolsa.util.Acao;
import java.awt.Component;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Pedro
 */
public class JFrameCliente extends javax.swing.JFrame implements ListListener {

    private ClienteBridge cliente;
    
    /** Creates new form JFrameCliente */
    public JFrameCliente() {
        initComponents();
        cliente = new ClienteBridge(new ClienteImplRMI());
        cliente.addListener(this);
        ativarCampos(jPanel2,Boolean.FALSE);
        setIconImage(new ImageIcon( getClass().getResource("/br/unifor/sd/bolsa/imgs/icone.jpg")).getImage());
        acaoComboBox.addItem("Escolha uma ação");
        for(int i=1;i<9;i++){
            acaoComboBox.addItem(i);
        }
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        ipLabel = new javax.swing.JLabel();
        jIp = new javax.swing.JTextField();
        portaLabel = new javax.swing.JLabel();
        jPorta = new javax.swing.JTextField();
        nickLabel = new javax.swing.JLabel();
        jNick = new javax.swing.JTextField();
        jConectar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableMinhasAcoes = new javax.swing.JTable();
        acaoLabel = new javax.swing.JLabel();
        acaoComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        valorTextField = new javax.swing.JTextField();
        comprarValorButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Cliente Bolsa de Valores");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Acesso"));

        ipLabel.setText("IP:");

        portaLabel.setText("Porta:");

        nickLabel.setText("Usuário:");

        jConectar.setText("Logar");
        jConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jConectarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(ipLabel)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jConectar))
                    .addComponent(nickLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jIp, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(portaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPorta, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jNick))
                .addContainerGap(205, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(portaLabel)
                    .addComponent(jPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ipLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jNick, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nickLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jConectar)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Ações"));

        jTableMinhasAcoes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jTableMinhasAcoes.setColumnSelectionAllowed(true);
        jScrollPane2.setViewportView(jTableMinhasAcoes);
        jTableMinhasAcoes.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        acaoLabel.setText("Ação:");

        jLabel1.setText("Valor:");

        comprarValorButton.setText("Comprar");
        comprarValorButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comprarValorButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 533, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(acaoLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(valorTextField)
                            .addComponent(acaoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(comprarValorButton))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(acaoLabel)
                    .addComponent(acaoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(valorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comprarValorButton)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(77, 77, 77))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-593)/2, (screenSize.height-573)/2, 593, 573);
    }// </editor-fold>//GEN-END:initComponents

    private void jConectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jConectarActionPerformed
        if(verificarCampos(jPanel1)){
            
            this.setTitle("Cliente Bolsa de Valores | Usuário - " + jNick.getText());
            cliente.setOwner(jNick.getText());
            ativarCampos(jPanel1, Boolean.FALSE);
            ativarCampos(jPanel2, Boolean.TRUE);
            new Thread() {

                public void run() {
                    try {
                        cliente.conect(jIp.getText(), Integer.parseInt(jPorta.getText()));
                        cliente.init();
                        cliente.listen();
                    } catch (Exception ex) {
                        Logger.getLogger(JFrameCliente.class.getName()).log(Level.SEVERE, null, ex);
                        if (ex instanceof UnknownHostException) {
                            JOptionPane.showMessageDialog(null, "Servidor não encontrado.", "Erro", JOptionPane.ERROR_MESSAGE);
                            ativarCampos(jPanel1, Boolean.TRUE);
                            ativarCampos(jPanel2, Boolean.FALSE);
                        }
                    }
                }
            }.start();

        } else {
            JOptionPane.showMessageDialog(null, "Preencha todos os campos.", "Aviso", JOptionPane.WARNING_MESSAGE);
        }
}//GEN-LAST:event_jConectarActionPerformed

    private void comprarValorButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comprarValorButtonActionPerformed
        try {
            if(acaoComboBox.getSelectedIndex() != -1 && acaoComboBox.getSelectedIndex() != 0 && !valorTextField.getText().equalsIgnoreCase("")){
                cliente.buyActionWithValue((Integer)acaoComboBox.getSelectedItem(),Double.parseDouble(valorTextField.getText()));
            }else{
                JOptionPane.showMessageDialog(this, "Selecione uma ação para ser comprada e o seu valor.", "Aviso", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            Logger.getLogger(JFrameCliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_comprarValorButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox acaoComboBox;
    private javax.swing.JLabel acaoLabel;
    private javax.swing.JButton comprarValorButton;
    private javax.swing.JLabel ipLabel;
    private javax.swing.JButton jConectar;
    private javax.swing.JTextField jIp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jNick;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jPorta;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableMinhasAcoes;
    private javax.swing.JLabel nickLabel;
    private javax.swing.JLabel portaLabel;
    private javax.swing.JTextField valorTextField;
    // End of variables declaration//GEN-END:variables

    public void onMessage(List<Acao> lista) {
        Vector data = new Vector();
        Vector colunas = null;
        Vector columnNames = new Vector();
        columnNames.add("Id");
        columnNames.add("Nome");
        columnNames.add("Valor");
        columnNames.add("Dono");
        
        for (int i = 0; i < lista.size(); i++) {
            colunas = new Vector();
            colunas.add(lista.get(i).getId());
            colunas.add(lista.get(i).getNome());
            colunas.add(lista.get(i).getValor());
            colunas.add(lista.get(i).getDono());
            data.add(colunas);
        }
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        jTableMinhasAcoes.setModel(model);
        jTableMinhasAcoes.repaint();
    }

    private void ativarCampos(JPanel jp, Boolean ativar) {
        Component components[] = jp.getComponents();
        for (int i = 0; i < components.length; i++) {
            ((Component) components[i]).setEnabled(ativar);
        }
    }

    private Boolean verificarCampos(JPanel jp) {
        Component components[] = jp.getComponents();
        for (int i = 0; i < components.length; i++) {
            if(((Component) components[i]) instanceof JTextField){
                if(((JTextField)((Component) components[i])).getText() != null &&
                   ((JTextField)((Component) components[i])).getText().equalsIgnoreCase("")){
                   return Boolean.FALSE;
                }
            }
        }
        return Boolean.TRUE;
    }
}
